package com.epfresh.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.DisplayImageOptions;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageScaleType;
import com.epfresh.api.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.tablayout.CommonTabLayout;
import com.epfresh.api.widget.tablayout.TabEntity;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.bean.ListGoods;
import com.epfresh.bean.StoreDetail;
import com.epfresh.fragment.CommonStoreGoodsFragment;
import com.epfresh.fragment.CommonStoreInfoFragment;
import com.epfresh.fragment.*;
import com.epfresh.global.BaseActivity;
import com.google.gson.Gson;

import java.util.ArrayList;


/**
 * Created by wzh on 16-9-9.
 */
public class CommonStoreActivity extends BaseActivity  implements OnTabSelectListener{

    private CommonTabLayout lyTab;
    //店铺名称
    private TextView tvStoreName;
    //市场名称
    private TextView tvMarketName;
    //关注数量
    private TextView tvLikeCount;
    //关注
    private TextView tvLike;
    //背景图片
    private ImageView ivBg;

    //店铺id
    private String storeId;

    private CommonStoreGoodsFragment commonStoreGoodsFragment;
    private CommonStoreInfoFragment storeInfoFragment;
    private WebFragment storeHomeWebFragment;

    private StoreDetail storeDetail;

    private String from;

    protected View getToolBar() {

        return null;
    }

    String[] mTitles;
    int[] mIconUnSelectIds;
    int[] mIconSelectIds;
    private void initFragmentView(int number) {
    /*"店铺首页","商品","供货商","店铺"*/

        if(number==4) {
            mTitles = new String[]{"店铺首页", "商品", "供货商", "店铺信息"};
            mIconUnSelectIds = new int[]{
                    R.mipmap.tab_store_home_unselect,
                    R.mipmap.tab_store_goods_unselect,
                    R.mipmap.tab_store_phone_unselect,
                    R.mipmap.tab_store_unselect};
            mIconSelectIds = new int[]{
                    R.mipmap.tab_store_home_select,
                    R.mipmap.tab_store_goods_select,
                    R.mipmap.tab_store_phone_select,
                    R.mipmap.tab_store_select};
        }else{
            mTitles = new String[]{"商品", "供货商", "店铺信息"};
            mIconUnSelectIds = new int[]{
                    R.mipmap.tab_store_goods_unselect,
                    R.mipmap.tab_store_phone_unselect,
                    R.mipmap.tab_store_unselect};
            mIconSelectIds = new int[]{
                    R.mipmap.tab_store_goods_select,
                    R.mipmap.tab_store_phone_select,
                    R.mipmap.tab_store_select};
        }

        ArrayList<TabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }
        lyTab = (CommonTabLayout) findViewById(R.id.ly_navigation);
        lyTab.setTabItemRes(R.layout.layout_tab_top);
        lyTab.setTabData(mTabEntities);
        //lyTab.setMsgMargin(2, LocalDisplay.dp2px(-10), 0);
        lyTab.setOnTabSelectListener(this);
        lyTab.setCurrentTab(0);//暂时先展示商品页面
        updatePageStatus(0);
    }


    @Override
    public void onTabSelect(int i) {
        updatePageStatus(i);
    }

    private void updatePageStatus(int i) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (commonStoreGoodsFragment != null) {
            transaction.hide(commonStoreGoodsFragment);
        }
        if (storeInfoFragment != null) {
            transaction.hide(storeInfoFragment);
        }
        if(storeHomeWebFragment != null){
            transaction.hide(storeHomeWebFragment);
        }
        if(mTitles!=null&&mTitles.length==3){
            if (i == 1) {
                if (storeDetail != null && storeDetail.getManagerPhone() != null)
                    openPhone(storeDetail.getManagerPhone());
                return;
            }else if (i == 0) {
                showGoodsFragment(transaction);
            } else if (i == 2) {
                showInfoFragment(transaction);
            }
            transaction.commit();
        }
        else if(mTitles!=null&&mTitles.length==4) {
            if (i == 2) {
                if (storeDetail != null && storeDetail.getManagerPhone() != null)
                    openPhone(storeDetail.getManagerPhone());
                return;
            }else if (i == 0) {
                showHomeFragment(transaction);
            } else if (i == 1) {
                showGoodsFragment(transaction);
            } else if (i == 3) {
                showInfoFragment(transaction);
            }
            transaction.commit();
        }
    }

    private void showHomeFragment(FragmentTransaction transaction){
        if (storeHomeWebFragment == null) {
            Bundle mBundle = new Bundle();
            //storeHomeWebFragment = WebFragment.getInstance(mBundle);
            storeHomeWebFragment = new WebFragment(storeDetail.getHomepage(),storeId);
            mBundle.putString(StoreHomeWebFragment.URL_KEY, storeDetail.getHomepage());
            transaction.add(R.id.content, storeHomeWebFragment, "0");
        }
        transaction.show(storeHomeWebFragment);
    }


    private void showGoodsFragment(FragmentTransaction transaction){
        if (commonStoreGoodsFragment == null) {
            commonStoreGoodsFragment = new CommonStoreGoodsFragment();
            if (storeDetail != null) {
                if (storeDetail.getIsAcceptOrders() == 0)
                    commonStoreGoodsFragment.isAcceptOrders = false;
                commonStoreGoodsFragment.updateData(storeDetail.getMergeGoods());
            }
            transaction.add(R.id.content, commonStoreGoodsFragment, "1");
        }
        transaction.show(commonStoreGoodsFragment);
    }

    private void showInfoFragment(FragmentTransaction transaction){
        if (storeInfoFragment == null) {
            storeInfoFragment = new CommonStoreInfoFragment();
            storeInfoFragment.updateData(storeDetail);
            transaction.add(R.id.content, storeInfoFragment, "2");
        }
        transaction.show(storeInfoFragment);
    }

    @Override
    public void onTabReselect(int i) {
/*        if(i==2){
            if (storeDetail != null && storeDetail.getManagerPhone() != null) {
                openPhone(storeDetail.getManagerPhone());
            }
        }else*/
            updatePageStatus(i);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_common_store_new);

        if (savedInstanceState != null) {
            getIntent().putExtra("storeId", savedInstanceState.getString("storeId"));
            getIntent().putExtra("from", savedInstanceState.getString("from"));
        }
        storeId = getIntent().getStringExtra("storeId");
        from = getIntent().getStringExtra("from");
        initView();


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("storeId", storeId);
        outState.putString("from",from);
    }

    @Override
    protected void onRestoreInstanceState(Bundle outState) {
        super.onRestoreInstanceState(outState);
        storeId = outState.getString("storeId");
    }

    private void initView() {
        initToolbar();
        initStoreHeaderView();
        requestStoreInfo();
    }

    protected void initToolbar() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        ivSearch = (ImageView) findViewById(R.id.iv_search);
    }

    private void initStoreHeaderView() {
        tvStoreName = (TextView) findViewById(R.id.tv_store_name);
        tvMarketName = (TextView) findViewById(R.id.tv_market_name);
        tvLikeCount = (TextView) findViewById(R.id.tv_like_count);
        tvLike = (TextView) findViewById(R.id.tv_like);
        tvLike.setOnClickListener(this);
        ivBg = (ImageView) findViewById(R.id.iv_bg);
        tvStoreName.setText("");
        tvMarketName.setText("");
    }

    public void openSearch(String storeId) {
        Intent search = new Intent(this, SearchByStoreActivity.class);
        search.putExtra("storeId", storeId);
        startActivity(search);
    }


    DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.background_store) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.mipmap.background_store)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.mipmap.background_store)
            .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
            .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565).build();

    public static DisplayImageOptions getAvatarOptions(String expectTag) {
        return new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.store_logo) // 设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.store_logo)// 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.store_logo) // 设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
                .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
                .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
                .displayer(new FadeInBitmapDisplayer(300, true, false, false))// 是否图片加载好后渐入的动画时间
                .setExceptTag(expectTag)
                .build();// 构建完成
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_like:
                if (storeDetail != null)
                    requestLike();
                break;
            case R.id.iv_back:
                if (from != null && from.equals("MarketMerchantFragment")) {
                    Intent intent = new Intent(this, GoodsAndMerchantActivity.class);
                    intent.putExtra("refresh", true);
                    startActivity(intent);
                }
                finish();
                break;
            case R.id.iv_search:
                openSearch(storeId);
                break;
        }
    }

    public void openPhone(String phone) {
        Intent call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));//调出来拨打页面；
        startActivity(call);
    }

    public void updateStoreInfo() {
        if (storeDetail != null) {
            tvMarketName.setText(storeDetail.getMarketShortName());
            tvStoreName.setText(storeDetail.getName());
            tvLikeCount.setText(storeDetail.getFavoriteCount() + "");
            updateLikeStatus();
            updateImage();
        }
    }

    public void updateImage() {
        if (storeDetail != null) {
            ImageLoader.getInstance().displayImage(storeDetail.getBackgroundImgUrl(), ivBg, options);
        }
    }

    public void updateLikeStatus() {
        if (storeDetail != null) {


            if (!storeDetail.isFavorite()) {
                tvLike.setText("关注");
                tvLike.setTextColor(Color.parseColor("#f39700"));
                Drawable drawable= getResources().getDrawable(R.mipmap.new_star);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                tvLike.setCompoundDrawables(drawable,null,null,null);
            } else {
                tvLike.setCompoundDrawables(null,null,null,null);
                tvLike.setTextColor(Color.parseColor("#434343"));
                tvLike.setText("已关注");
            }
        }
    }

    OnRequestListener<StoreDetail> onStoreRequestListener = new OnRequestListener<StoreDetail>() {
        @Override
        public StoreDetail jsonToObj(String s) {
            return new Gson().fromJson(s, StoreDetail.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();

        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StoreDetail> responseEntity, Object o) {
            hideProgressDialog();
            StoreDetail responseElement = responseEntity.getResponseElement();

            if (responseElement != null) {

                storeDetail = responseElement;
                updateStoreInfo();
                if(storeDetail.getHomepage()!=null&&!"".equals(storeDetail.getHomepage())){
                    initFragmentView(4);
  //                  Log.e("4___getHomepage",storeDetail.getHomepage());
                }else{
                    initFragmentView(3);
//                    Log.e("3___getHomepage",storeDetail.getHomepage());
                }
                if (storeInfoFragment != null) {
                    storeInfoFragment.updateData(storeDetail);
                }
                if (commonStoreGoodsFragment != null) {
                    commonStoreGoodsFragment.updateData(storeDetail.getMergeGoods());
                }
            } else {

            }

        }
    };

    public void requestStoreInfo() {
        RequestEntityMap rm = new RequestEntityMap();
        rm.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_load);
        rm.putParameter("storeId", storeId);
        request(rm, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_load, onStoreRequestListener);
    }

    OnRequestListener onLikeRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String s) {
            return new Gson().fromJson(s, StatusEntity.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> responseEntity, Object o) {
            hideProgressDialog();
            StatusEntity responseElement = responseEntity.getResponseElement();
            if (responseElement.isSuccess()) {
                if (storeDetail != null) {
                    boolean isFavorite = !storeDetail.isFavorite();
                    int favoriteCount = storeDetail.getFavoriteCount();
                    storeDetail.setFavorite(isFavorite);
                    if (isFavorite) {
                        ++favoriteCount;
                        T.toast("已关注");
                    } else {
                        --favoriteCount;
                        T.toast("已取消");
                    }
                    storeDetail.setFavoriteCount(favoriteCount);
                }
                updateStoreInfo();
                if (commonStoreGoodsFragment != null) {
                    commonStoreGoodsFragment.updateData(storeDetail.getMergeGoods());
                }
                if (storeInfoFragment != null) {
                    storeInfoFragment.updateData(storeDetail);
                }
            } else {
                T.toast(ApplicationHelper.getInstance().getDoc().getNetWeak());
            }
        }
    };

    public void requestLike() {
        RequestEntityMap rm = new RequestEntityMap();
        String cmd = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_coupon_favorite_save;
        if (storeDetail != null && storeDetail.isFavorite()) {
            cmd = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_coupon_favorite_cancel;
        }
        if (storeDetail != null)
            rm.putParameter("name", storeDetail.getName());
        rm.setCmd(cmd);
        rm.putParameter("type", 1);
        rm.putParameter("targetId", storeId);
        request(rm, cmd, onLikeRequestListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
